package com.zhf.JDBC04;

import com.zhf.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/23 22:23
 */
public class TestJDBCTransaction {

    //使用JDBC操作事务
    public static void main(String[] args) {

        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try {
            //获取连接
            connection = JDBCUtils.getConnection();

            //开启事务
            connection.setAutoCommit(false);//手动提交事务

            //获取预处理对象执行SQL
            preparedStatement = connection.prepareStatement("update account set money=money-? where name=?");
            preparedStatement.setInt(1,500);
            preparedStatement.setString(2,"tom");
            preparedStatement.executeUpdate();

            System.out.println(11/0);
            preparedStatement = connection.prepareStatement("update account set money=money+? where name=?");
            preparedStatement.setInt(1,500);
            preparedStatement.setString(2,"jack");
            preparedStatement.executeUpdate();

            //提交事务
            connection.commit();

        } catch (SQLException e) {
            e.printStackTrace();
            //出现异常回滚事务
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            //释放资源
            JDBCUtils.close(connection,preparedStatement);
        }

    }
}
